<template>
  <div>
    <van-form ref="form">
      <van-field
        readonly
        clickable
        name="是否代他人报备"
        is-link
        label="是否代他人报备"
        required
        :disabled="this.isEdit"
        :value="formData.isSelfFlagLabel"
        placeholder="请选择是否代他人报备"
        @click="isEdit?showIsSelfPicker = false : showIsSelfPicker = true"
        :rules="rules.isSelfFlag"
      />
      <van-field
        v-model="formData.reportor"
        autocomplete="off"
        clearable
        required
        :disabled="isSelfFlag"
        name="姓名"
        label="姓名"
        placeholder="姓名"
        :rules="rules.reportor"
      />
      <van-field
        readonly
        clickable
        name="员工性质"
        is-link
        label="员工性质"
        required
        :value="formData.empNatureLabel"
        placeholder="请选择员工性质"
        @click="showEmpNaturePicker = true"
        :rules="rules.empNature"
      />
      <van-field
        v-model="formData.tel"
        autocomplete="off"
        clearable
        required
        maxlength="11"
        name="联系方式"
        label="联系方式"
        placeholder="联系方式"
        :rules="rules.tel"
      />
      <van-field
        v-model="areaValue"
        is-link
        readonly
        required
        label="出行地区"
        placeholder="请选择出行地区"
        @click="areaShow = true"
        :rules="rules.provCode"
      />
      <van-popup v-model="areaShow" round position="bottom">
        <van-cascader
          v-model="cascaderValue"
          title="请选择出行地区"
          :options="dataList"
          @close="areaShow = false"
          @change="loadData"
          @finish="onFinish"
        />
      </van-popup>
      <van-field
        readonly
        clickable
        name="出行类型"
        is-link
        label="出行类型"
        required
        :value="formData.tripTypeLabel"
        placeholder="请选择出行类型"
        @click="showTripTypePicker = true"
        :rules="rules.tripType"
      />
      <van-field
        readonly
        clickable
        name="出行方式"
        is-link
        label="出行方式"
        required
        :value="formData.tripMethodLabel"
        placeholder="请选择出行方式"
        @click="showTripMethodPicker = true"
        :rules="rules.tripMethod"
      />
      <van-field
        readonly
        clickable
        name="是否省外"
        is-link
        label="是否省外"
        required
        :value="formData.isOutProvinceLabel"
        placeholder="请选择是否省外"
        @click="showOutProvincePicker = true"
        :rules="rules.isOutProvince"
      />
      <van-field
        readonly
        clickable
        required
        :value="dateInterval"
        label="往返时间"
        placeholder="点击选择日期"
        :rules="rules.dateInterval"
        @click="dateShow = true"
      />
      <van-calendar
        v-model="dateShow"
        :min-date="minDate"
        :max-date="maxDate"
        :show-confirm="false"
        type="range"
        :allow-same-day="true"
        @confirm="onConfirm"
      />
      <van-field
        v-model="formData.addr"
        autocomplete="off"
        clearable
        required
        name="出行详细地址"
        label="出行详细地址"
        placeholder="出行详细地址"
        :rules="rules.addr"
      />
      <van-field
        v-model="formData.tripReason"
        rows="5"
        name="出行原因"
        label="出行原因"
        required
        type="textarea"
        maxlength="256"
        placeholder="请输入出行原因"
        show-word-limit
        :rules="rules.tripReason"
      />
      <van-button class="defaultBtn" @click="handleSave">保存</van-button>
    </van-form>
    <fullLoading v-if="loading"></fullLoading>
    <!-- 是否代他人报备选择 -->
    <van-action-sheet
      v-model="showIsSelfPicker"
      cancel-text="取消"
      :actions="isSelfCodeData"
      @select="onIsSelfConfirm"
    />
    <!-- 员工性质选择 -->
    <van-action-sheet
      v-model="showEmpNaturePicker"
      cancel-text="取消"
      :actions="saEmpNatureCodeData"
      @select="onEmpNaturefirm"
    />
    <!-- 出行类型选择 -->
    <van-action-sheet
      v-model="showTripTypePicker"
      cancel-text="取消"
      :actions="tripTypeCodeData"
      @select="onTripTypeConfirm"
    />
    <!-- 出行方式选择 -->
    <van-action-sheet
      v-model="showTripMethodPicker"
      cancel-text="取消"
      :actions="tripMethodCodeData"
      @select="onTripMethodConfirm"
    />
    <!-- 是否省外选择 -->
    <van-action-sheet
      v-model="showOutProvincePicker"
      cancel-text="取消"
      :actions="isOutProvinceCodeData"
      @select="onOutProveinceConfirm"
    />
  </div>
</template>
<script>
import { saveTravelReport } from "@/api/srvAssurance/epidprevention/travel/travel";
import { queryDic, queryArea } from "@/api/common";
export default {
  data() {
    return {
      showIsSelfPicker: false, // 是否代他人报备picker
      showEmpNaturePicker: false, // 员工性质picker
      showTripTypePicker: false, // 出行类型picker
      showTripMethodPicker: false, // 出行方式picker
      showOutProvincePicker: false, // 是否省外picker
      showStartTimePicker: false, // 开始时间
      showEndTimePicker: false, // 竣工时间
      areaShow: false, //区域show
      dateShow: false, //日期show
      minDate: new Date(new Date().getFullYear() - 1, 0, 1),
      maxDate: new Date(new Date().getFullYear(), 11, 31),
      areaValue: "", //所选地区
      cascaderValue: "",
      isSelfFlag: false, //是否代报备disable
      dateInterval: "", //时间区间
      formData: {
        tripReportId: "", // 开工报告标识
        reportor: "", // 姓名
        tel: "", //电话
        empNature: "", // 员工性质
        empNatureLabel: "",
        isSelfFlag: "", // 是否代填报
        isSelfFlagLabel: "",
        provCode: "",
        cityCode: "",
        areaCode: "",
        tripType: "", // 出行类型
        tripTypeLabel: "",
        tripMethod: "", // 出行方法
        tripMethodLabel: "",
        isOutProvince: "", // 是否省外
        isOutProvinceLabel: "",
        leaveDate: "", // 出发时间
        returnDate: "", // 返回时间
        addr: "", // 出行地址
        tripReason: "", //出行原因
        isAdmin: "0",
      },
      rules: {
        reportor: [
          { required: true, message: "请输入姓名", trigger: "onBlur" },
        ],
        tel: [
          { required: true, message: "请填写手机号码", trigger: "onBlur" },
          {
            pattern: this.$commonReg.phoneReg,
            message: this.$commonReg.phoneMsg,
            trigger: "onBlur",
          },
        ],
        provCode: [
          { required: true, message: "请选择出行地区", trigger: "blur" },
        ],
        tripType: [
          { required: true, message: "请选择出行类型", trigger: "onChange" },
        ],
        tripMethod: [
          { required: true, message: "请选择出行方式", trigger: "onChange" },
        ],
        empNature: [
          { required: true, message: "请选择员工性质", trigger: "onChange" },
        ],
        isSelfFlag: [
          {
            required: true,
            message: "请选择是否代他人填报",
            trigger: "onChange",
          },
        ],
        isOutProvince: [
          {
            required: true,
            message: "请选择是否代他人填报",
            trigger: "onChange",
          },
        ],
        dateInterval: [
          {
            required: true,
            message: "请选择往返时间",
            trigger: "onChange",
          },
        ],
        tripReason: [
          { required: true, message: "请填写出行原因", trigger: "blur" },
        ],
        addr: [
          { required: true, message: "请填写出行详细地址", trigger: "blur" },
        ],
      },
      dataList: [],
      supvUnitList: [], // 监理单位
      isSelfCodeData: [], // 是否代报备dic
      saEmpNatureCodeData: [], // 员工性质dic
      tripTypeCodeData: [], // 出行类型dic
      tripMethodCodeData: [], // 出行方法dic
      isOutProvinceCodeData: [], // 是否省外dic
      isEdit: false,
      loading: false,
      reportDefaultFiles: [], // 附件
      reportFile: [],
      deleteAttachIdArr: [],
      // 审批人
      handlerModal: false,
      checkedArr: [],
      handlerList: [],
      handlerIds: [],
      handlers: [],
    };
  },
  mounted() {
    this.getDicData();
    this.getInitTree();
  },
  methods: {
    getInitTree() {
      queryArea("", "1").then((res) => {
        if (res.code == "1000") {
          let data = res.data;
          data = this.operationTree(data);
          this.dataList = data;
        }
      });
    },
    loadData(item) {
      item.loading = true;
      queryArea(item.value,  Number(item.tabIndex) + 2).then((res) => {
        item.loading = false;
        if (res.code == "1000") {
          let data = res.data;
          data = this.operationTree(data);
          if (item.tabIndex == 0) {
            item.selectedOptions[0].children = data;
          } else {
            item.selectedOptions[1].children = data;
          }
        }
      });
    },
    operationTree(arr) {
      let arrData = [];
      arr.forEach((item) => {
        if (item.areaLevel > 2) {
          arrData.push({
            value: item.areaCode,
            text: item.areaName,
          });
        } else {
          arrData.push({
            value: item.areaCode,
            text: item.areaName,
            level: item.areaLevel,
            children: [],
            // loading: false,
          });
        }
      });
      return arrData;
    },
    // 全部选项选择完毕后，会触发 finish 事件
    onFinish(item) {
      this.areaShow = false;
      this.areaValue = item.selectedOptions
        .map((option) => option.text)
        .join("/");
      this.formData.provCode = item.selectedOptions[0].value;
      this.formData.cityCode = item.selectedOptions[1].value;
      this.formData.areaCode = item.selectedOptions[2].value;
    },
    // 获取字典数据
    getDicData() {
      // 是否代他人报备和是否省外
      queryDic("IS_FLAG_CODE").then((res) => {
        if (res.code == "1000" && res.data) {
          this.isSelfCodeData = res.data;
          this.isOutProvinceCodeData = res.data;
        }
      });
      //员工性质
      queryDic("SA_EMP_NATURE_CODE").then((res) => {
        if (res.code == "1000" && res.data) {
          this.saEmpNatureCodeData = res.data;
        }
      });
      //出行类型
      queryDic("SA_TRIP_TYPE_CODE").then((res) => {
        if (res.code == "1000" && res.data) {
          this.tripTypeCodeData = res.data;
        }
      });
      //出行方式
      queryDic("SA_TRIP_METHOD_CODE").then((res) => {
        if (res.code == "1000" && res.data) {
          this.tripMethodCodeData = res.data;
        }
      });
    },
    // 保存
    handleSave() {
      this.loading = true;
      this.$refs.form
        .validate()
        .then(async () => {
          let formData = { ...this.formData };
          if (!this.isEdit) {
            // 新增
            delete formData.tripReportId;
          }
          //新增或修改基本信息
          this.loading = false;
          let res = await saveTravelReport(formData);
          if (res.code == "1000"  && res.data == true) {
            this.$Notify({ type: "success", message: "保存成功！" });
            this.$emit("close");
            this.$emit("refresh");
          } else {
            this.$Notify({ type: "warning", message: "保存失败！" });
          }
        })
        .catch(() => {
          this.loading = false;
        });
    },
    // 查询原本信息
    getData(obj) {
      this.isEdit = true;
      for (var key in this.formData) {
        if (obj[key] || obj[key] === 0) {
          this.formData[key] = obj[key];
        }
      }
      this.dateInterval =
      this.formData.leaveDate + " / " + this.formData.returnDate;
      this.areaValue = obj.provName + obj.cityName + obj.areaName;
      //判断隔离类型
      this.judgeSelfFlagType(this.isEdit);
    },
    //判断是否代填报类型
    judgeSelfFlagType(isEdit) {
      if (this.formData.isSelfFlag == 0) {
        let userInfo = JSON.parse(sessionStorage.getItem("userInfo"));
        this.formData.reportor = userInfo.name;
        this.isSelfFlag = true;
      } else if (!isEdit) {
        this.formData.reportor = "";
        this.isSelfFlag = false;
      } else {
        this.isSelfFlag = false;
      }
    },
    // 是否代他人报备选择
    onIsSelfConfirm(item) {
      this.formData.isSelfFlag = item.value;
      this.formData.isSelfFlagLabel = item.text;
      this.judgeSelfFlagType(this.isEdit);
      this.showIsSelfPicker = false;
    },
    // 员工性质选择
    onEmpNaturefirm(item) {
      this.formData.empNature = item.value;
      this.formData.empNatureLabel = item.text;
      this.showEmpNaturePicker = false;
    },
    // 出行方式选择
    onTripTypeConfirm(item) {
      this.formData.tripType = item.value;
      this.formData.tripTypeLabel = item.text;
      this.showTripTypePicker = false;
    },
    // 出行类型选择
    onTripMethodConfirm(item) {
      this.formData.tripMethod = item.value;
      this.formData.tripMethodLabel = item.text;
      this.showTripMethodPicker = false;
    },
    // 是否省外选择
    onOutProveinceConfirm(item) {
      this.formData.isOutProvince = item.value;
      this.formData.isOutProvinceLabel = item.text;
      this.showOutProvincePicker = false;
    },
    //日期格式
    formatDate(date) {
      return `${date.getFullYear()}-${
        date.getMonth() < 9
          ? "0" + (date.getMonth() + 1)
          : "" + (date.getMonth() + 1)
      }-${date.getDate() < 10 ? "0" + date.getDate() : "" + date.getDate()}`;
    },
    // 开始时间选择
    onConfirm(date) {
      this.formData.leaveDate = this.formatDate(date[0]);
      this.formData.returnDate = this.formatDate(date[1]);
      this.dateInterval = `${this.formatDate(date[0])} / ${this.formatDate(
        date[1]
      )}`;
      this.dateShow = false;
    },
    // 重置表单
    resetForm() {
      this.formData = {
        tripReportId: "", // 开工报告标识
        reportor: "", // 姓名
        tel: "", //电话
        empNature: "", // 员工性质
        empNatureLabel: "",
        isSelfFlag: "", // 是否代填报
        isSelfFlagLabel: "",
        provCode: "",
        cityCode: "",
        areaCode: "",
        tripType: "", // 出行类型
        tripTypeLabel: "",
        tripMethod: "", // 出行方法
        tripMethodLabel: "",
        isOutProvince: "", // 是否省外
        isOutProvinceLabel: "",
        leaveDate: "", // 出发时间
        returnDate: "", // 返回时间
        addr: "", // 出行地址
        tripReason: "", //出行原因
        isAdmin: "0",
      };
      this.dateInterval = "";
      this.isSelfFlag = false;
      this.isEdit = false;
      this.areaValue = "";
      setTimeout(() => {
        this.$refs.form.resetValidation();
      });
    },
  },
};
</script>
